package com.book.controller;

import com.book.common.BaseController;
import com.book.common.CommonResult;
import com.book.common.NoRepeatSubmit;
import com.book.dto.UserDto;
import com.book.redis.SessionProvider;
import com.book.remote.UserRemote;
import com.book.util.Constants;
import com.book.util.MD5Utils;
import com.book.vo.ResponseVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @Author 李锦程
 * @Date 2021/4/2 6:03 下午
 * @Package com.book.controller
 * @Version 1.0
 */
@Slf4j
@Controller
@RequestMapping("/user")
public class UserController extends BaseController {
    @Autowired
    private UserRemote userApi;
    @Autowired
    private SessionProvider sessionProvider;

    @RequestMapping("phoneCheck")
    @ResponseBody
    public String phoneCheck(UserDto userDto) {
        try {
            if (userDto != null) {
                Boolean aBoolean = userApi.userPhoneCheck(userDto);
                if (aBoolean) {
                    return "1";
                }
            }
            return "0";
        } catch (Exception e) {
            log.info(this.getClass().getName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName(), e);
            return "校验失败";
        }
    }

    @RequestMapping("/checkEmail")
    @ResponseBody
    public String checkEmail(UserDto userDto) {
        try {
            if (userDto != null) {
                Boolean aBoolean = userApi.userEmailCheck(userDto);
                if (aBoolean) {
                    return "1";
                }
            }
            return "0";
        } catch (Exception e) {
            log.info(this.getClass().getName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName(), e);
            return "校验失败";
        }
    }

    @RequestMapping("/checkName")
    @ResponseBody
    public String checkName(UserDto userDto) {
        try {
            if (userDto != null) {
                Boolean aBoolean = userApi.userNameCheck(userDto);
                if (aBoolean) {
                    return "1";
                }
            }
            return "0";
        } catch (Exception e) {
            log.info(this.getClass().getName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName(), e);
            return "校验失败";
        }
    }

    @NoRepeatSubmit
    @RequestMapping("/doRegister")
    @ResponseBody
    public CommonResult doRegister(UserDto userDto) {
        try {
            if (userDto != null) {
                if (StringUtils.isEmpty(userDto.getUEmail()) || userDto.getUEmail().trim().length() == 0) {
                    userDto.setUEmail(null);
                }
                if (StringUtils.isEmpty(userDto.getUPhone()) || userDto.getUPhone().trim().length() == 0) {
                    userDto.setUPhone(null);
                }
                Integer register = userApi.register(userDto);
                log.info("UserController register i:{}",register);
                return 1 == 1 ? CommonResult.successNoMsg():CommonResult.fail("注册失败");
            }
            return CommonResult.fail("填写信息不能为空");
        }catch (Exception e){
            log.info("UserController register error",e);
            return CommonResult.fail("注册失败");
        }
    }

    @RequestMapping("/login")
    @ResponseBody
    public String login(UserDto userDto, Integer remeberMe, HttpSession session, HttpServletResponse response, HttpServletRequest request) {
        try {
            String pass = userDto.getUPass();
            userDto.setUPass(MD5Utils.MD5Encode(userDto.getUPass(), "utf-8"));
            UserDto userDto1 = userApi.doLogin(userDto);
            log.info("userDto1:{}", userDto1);
            if (userDto1.getUCode() != null) {
                setSessionCookieId(userDto1);
                log.info("login.rememberMe:{}", remeberMe);
                userDto.setUPass(pass);
                addCookie(userDto, remeberMe, response);
                return Constants.SUCCESS;
            }
        } catch (Exception e) {
            log.error("登录失败", e);
            return Constants.ERROR;
        }
        return Constants.ERROR;
    }

    @RequestMapping("/getCookie")
    @ResponseBody
    public UserDto getCookie(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        UserDto userDto = new UserDto();

        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                if ("account".equals(cookie.getName())) {
                    userDto.setUPhone(cookie.getValue());
                    userDto.setUEmail(cookie.getValue());
                }
                if ("pass".equals(cookie.getName())) {
                    userDto.setUPass(cookie.getValue());
                }
            }
        }
        return userDto;
    }

    private void addCookie(UserDto userDto, Integer rememberMe, HttpServletResponse response) {
        if (userDto != null) {
            Cookie loginAccountCookie = new Cookie("account", userDto.getUPhone());
            Cookie loginPasswordCookie = new Cookie("pass", userDto.getUPass());
            if (rememberMe == null) {
                loginAccountCookie.setMaxAge(0);
                loginPasswordCookie.setMaxAge(0);
            } else {
                log.info("#saveCookie#remeberMe:{}", rememberMe);
                loginAccountCookie.setMaxAge(7 * 24 * 60 * 60);
                loginPasswordCookie.setMaxAge(7 * 24 * 60 * 60);
                response.addCookie(loginAccountCookie);
                response.addCookie(loginPasswordCookie);
            }
        }
    }

    @RequestMapping("/shop/car/{id}/index")
    public String getShopCar(@PathVariable Integer id, HttpServletRequest request, HttpServletResponse response, Model model) {
        log.info("id:{}", id);
        return "index.jsp";
    }

    @RequestMapping("/myInfo")
    public String myInfo(Model model) {
        UserDto currentUser = getCurrentUser();
        model.addAttribute("user", currentUser);
        return "/user/myInfo.jsp";
    }

    @RequestMapping("/userInfo/")
    public String userInfo() {
        return "/user/userInfo.jsp";
    }

    @RequestMapping("/editName")
    @ResponseBody
    public ResponseVo editName(String name) {
        if (StringUtils.isEmpty(name)) {
            return ResponseVo.errRest("用户名不能为空");
        }
        Integer count = userApi.getCountByName(name);
        if (count == 0 || (count == 1 && getCurrentName().equals(name))) {
            UserDto userDto = new UserDto();
            userDto.setId(getCurrentUser().getId());
            userDto.setUName(name);
            Boolean aBoolean = userApi.updateUser(Constants.USER_NAME, name, getCurrentName(), userDto);
            if (aBoolean) {
                getCurrentUser().setUName(name);
                return ResponseVo.successResultNotData();
            }
            return ResponseVo.errRest("修改失败");
        }
        return ResponseVo.errRest("用户名已存在");
    }

    @RequestMapping("/editPhone")
    @ResponseBody
    public ResponseVo editPhone(String phone) {
        if (StringUtils.isEmpty(phone)) {
            return ResponseVo.errRest("号码不能为空");
        }
        Integer count = userApi.getCountByPhone(phone);
        if (count == 0 || (count == 1 && getCurrentPhone().equals(phone))) {
            UserDto userDto = new UserDto();
            userDto.setId(getCurrentUser().getId());
            userDto.setUPhone(phone);
            Boolean aBoolean = userApi.updateUser(Constants.USER_PHONE, phone, getCurrentPhone(), userDto);
            if (aBoolean) {
                getCurrentUser().setUPhone(phone);
                return ResponseVo.successResultNotData();
            }
            return ResponseVo.errRest("修改失败");
        }
        return ResponseVo.errRest("号码已存在");
    }

    @RequestMapping("/editEmail")
    @ResponseBody
    public ResponseVo editEmail(String email) {
        if (StringUtils.isEmpty(email)) {
            return ResponseVo.errRest("邮箱不能为空");
        }
        Integer count = userApi.getCountByEmail(email);
        if (count == 0 || getCurrentEmail() == null || (count == 1 && getCurrentEmail().equals(email))) {
            UserDto userDto = new UserDto();
            userDto.setId(getCurrentUser().getId());
            userDto.setUEmail(email);
            Boolean aBoolean = userApi.updateUser(Constants.USER_EMAIL, email, getCurrentEmail(), userDto);
            if (aBoolean) {
                getCurrentUser().setUEmail(email);
                return ResponseVo.successResultNotData();
            }
            return ResponseVo.errRest("修改失败");
        }
        return ResponseVo.errRest("邮箱已存在");
    }


    @RequestMapping("/editPassPage")
    public String editPass(Model model) {
        String phone = getCurrentPhone();
        String email = getCurrentEmail();
        if (StringUtils.isNotEmpty(phone)) {
            String s1 = phone.substring(0, 2);
            String s2 = phone.substring(phone.length() - 2);
            model.addAttribute("myPhone", s1 + "*******" + s2);
        }
        if (StringUtils.isNotEmpty(email)) {
            String[] split = email.split("@");
            String s1 = split[0].substring(0, 2);
            model.addAttribute("myEmail", s1 + "******." + split[1]);
        }
        return "/user/editPassword.jsp";
    }

    @RequestMapping("/editPassword")
    @ResponseBody
    public ResponseVo editPassword(String oldValue, String newValue) {
        try {
            String s = MD5Utils.MD5Encode(oldValue, "utf-8");
            if (!s.equals(getCuurentPass())) {
                return ResponseVo.errRest("旧密码输入错误");
            }
            Boolean aBoolean = userApi.updatePassword(MD5Utils.MD5Encode(newValue, "utf-8"), getUserCode());
            return aBoolean ? ResponseVo.successResultNotData() : ResponseVo.errRest("修改密码失败");
        } catch (Exception e) {
            return ResponseVo.errRest("修改密码失败");
        }
    }

    @RequestMapping("/validAccount")
    @ResponseBody
    public ResponseVo validAccount(String account) {
        try {
            Boolean aBoolean = userApi.validAccount(account.trim(), getUserCode());
            return aBoolean ? ResponseVo.successResultNotData() : ResponseVo.errRest("验证失败");
        } catch (Exception e) {
            return ResponseVo.errRest("验证失败");
        }
    }

    @RequestMapping("/loginout")
    public String loginOut(HttpServletResponse response) {
        clearSession();
        clearCookie();
        return "login.jsp";
    }
}
